package com.lidong.lowcode.core.config.rebbitmq.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidong.config.domain.logs.SysLogDTO;
import com.lidong.config.domain.rabbitqueue.QueueConst;
import com.lidong.config.utils.es.EsUtils;
import com.lidong.lowcode.core.domain.system.InterfaceRequestLog;
import com.lidong.lowcode.core.service.system.SyslogService;
import com.lidong.toolkit.constant.NumConst;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * 日志注解拦截的日志放到队列后在这里进行入库操作
 *
 * @author LiDong
 * @Create：2021/1/13
 * @Version：1.0.0
 */
@Component
public class OsCoreRabbitMqConsume {

    @Autowired(required = false)
    private RestHighLevelClient esClient;

    @Autowired
    private SyslogService syslogService;


    private static final Logger logger = LoggerFactory.getLogger(OsCoreRabbitMqConsume.class);

    /**
     * 日志队列
     */
    private List<InterfaceRequestLog> logList = new LinkedList<>();

    /**
     * 监听全局的日志队列、有日志生成放到队列，进行操作
     */
    @RabbitListener(queues = QueueConst.GLOBAL_LOG_QUEUE)
    @RabbitHandler
    public void dealSysLogs(String message) {
        logger.info("\n===========> RabbitMq 队列 { " + QueueConst.GLOBAL_LOG_QUEUE + " } 收到信息：{}", message);
        try {
            // 日志入Es
            if (!EsUtils.isExistsIndex(esClient, QueueConst.GLOBAL_LOG_QUEUE)) {
                EsUtils.createIndex(esClient, QueueConst.GLOBAL_LOG_QUEUE);
            }
            EsUtils.addDocument(esClient, QueueConst.GLOBAL_LOG_QUEUE, JSON.parse(message));

        } catch (Exception e) {
            logger.error("=====> dealSysLogs()日志入Es出错：{}", e.getMessage());
        }
        try {
            SysLogDTO sysLogDTO = JSON.parseObject(message, SysLogDTO.class);
            InterfaceRequestLog logDto = new InterfaceRequestLog();
            BeanUtils.copyProperties(sysLogDTO, logDto);
            if (NumConst.Ten > logList.size()) {
                logList.add(logDto);
            }
        } catch (Exception e) {
            logger.error("=====> dealSysLogs()日志入数据库出错：{}", e.getMessage());
        } finally {
            // 重置当前的list
            if (NumConst.Ten <= logList.size()) {
                // 日志入库
                syslogService.insertInterfaceRequestLogBatch(logList);
                logList = new LinkedList<>();
            }
        }
    }

}
